package com.ztom.v2;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhangTao
 */
public class Code59GenerateParentheses {

    public List<String> generateParenthesis(int n) {
        if (n == 0) {
            return new ArrayList<>();
        }
        List<String> res = new ArrayList<>();
        process(res, 0, 0, n, new StringBuilder());
        return res;
    }

    public void process(List<String> res, int ln, int rn, int n, StringBuilder path) {
        if (ln > n || rn > n || rn > ln) {
            return;
        }
        if (ln == n && rn == n) {
            res.add(path.toString());
            return;
        }
        // 当前生成 (
        path.append("(");
        process(res, ln + 1, rn, n, path);
        path.deleteCharAt(path.length() - 1);
        // 当前生成 )
        path.append(")");
        process(res, ln, rn + 1, n, path);
        path.deleteCharAt(path.length() - 1);
    }
}
